package com.asimplefox.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.asimplefox.entity.PaypalOrder;
import com.asimplefox.entity.Role;
import com.asimplefox.entity.User;
import com.asimplefox.entity.paypal.PayPalOrder;
import com.asimplefox.mapper.PaypalOrderMapper;
import com.asimplefox.serurity.TokenManager;
import com.asimplefox.serurity.UserRoleDetails;
import com.asimplefox.service.IPaypalOrderService;
import com.asimplefox.service.IRoleService;
import com.asimplefox.service.abst.ResultU;
import com.asimplefox.service.abst.ServiceImplAll;
import com.asimplefox.service.stand.PayPalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import static com.asimplefox.controllers.PayPalController.priceMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kloping
 * @since 2024-11-26
 */
@Service
@Slf4j
public class PaypalOrderServiceImpl extends ServiceImplAll<PaypalOrderMapper, PaypalOrder> implements IPaypalOrderService {
    @Override
    public String backCap(String token, String payerID) throws IOException {
        PaypalOrder paypalOrder = lambdaQuery().eq(PaypalOrder::getId, token).one();
        if (paypalOrder.getStatus().equalsIgnoreCase("COMPLETED")) {
            return success("订单已完成，无需再次确认(The order has been completed and does not need to be reconfirmed)");
        }
        JSONObject jd = payPalService.capture(token);

        if (jd == null || jd.isEmpty() || !jd.containsKey("id")) {
            return result(400, "支付未完成", ResultU.Kv.of("status", jd.getString("message")));
        }

        String pid = jd.getString("id");
        if (!pid.equalsIgnoreCase(token.trim())) return result(400, "this is impossible!");
        lambdaUpdate().eq(PaypalOrder::getId, pid).set(PaypalOrder::getOpt, "capture")
                .set(PaypalOrder::getData, jd.toJSONString()).update();

        paypalOrder = lambdaQuery().eq(PaypalOrder::getId, pid).one();

        if (jd.getString("status").equalsIgnoreCase("COMPLETED")) {
            subscribeNow(paypalOrder);
            return success("支付成功");
        } else return result(400, "支付未完成", ResultU.Kv.of("status", jd.getString("status")));
    }

    /**
     * 暂时只用
     *
     * @param token
     * @return
     * @throws IOException
     */
    @Override
    public String cancel(String token) throws IOException {
        PaypalOrder paypalOrder = lambdaQuery().eq(PaypalOrder::getId, token).one();
        if (paypalOrder.getStatus().equalsIgnoreCase("COMPLETED")) {
            return fail("订单已完成，无法取消");
        }
        JSONObject jd = payPalService.query(token);
        lambdaUpdate().eq(PaypalOrder::getId, token).set(PaypalOrder::getStatus, "CANCELED")
                .set(PaypalOrder::getData, jd.toJSONString())
                .set(PaypalOrder::getOpt, "cancel")
                .update();
        return result(200, "取消成功");
    }

    @Override
    public String create(UserRoleDetails details, Integer price) throws IOException {
        if (priceMap.containsKey(price)) {
            PayPalOrder payPalOrder = payPalService.order(details.getUsername(), priceMap.get(price) + "度订阅", price + ".00");
            save(new PaypalOrder().setId(payPalOrder.getId()).setOpt("create").setPrice(price).setUid(details.getUser().getId()).setData(JSON.toJSONString(payPalOrder)));
            if (payPalOrder.getStatus().equalsIgnoreCase("CREATED")) {
                String purl = null;
                for (PayPalOrder.Link link : payPalOrder.getLinks()) {
                    if (link.getRel().equalsIgnoreCase("approve")) {
                        purl = link.getHref();
                    }
                }
                return result(200, "订单创建成功", Kv.of("payurl", purl), Kv.of("pay_id", payPalOrder.getId()));
            } else return fail("创建订单失败");
        } else return fail("未发现相关订阅套餐(No related subscription plans found)");
    }

    @Override
    public String query(String id) throws IOException {
        JSONObject jd = payPalService.query(id);
        lambdaUpdate().eq(PaypalOrder::getId, id).set(PaypalOrder::getData, jd.toJSONString()).set(PaypalOrder::getStatus, jd.getString("status")).set(PaypalOrder::getOpt, "query").update();
        return jd.toJSONString();
    }

    @Override
    public List list(User user) {
        List<PaypalOrder> list = lambdaQuery().eq(PaypalOrder::getUid, user.getId()).list();
        List<JSONObject> ld = list.stream().map(paypalOrder -> {
            JSONObject jo = new JSONObject();
            jo.put("id", paypalOrder.getId());
            jo.put("price", paypalOrder.getPrice());
            jo.put("status", paypalOrder.getStatus());
            try {
                JSONObject data = JSON.parseObject(paypalOrder.getData());
                jo.put("create_time", data.getString("create_time"));
            } catch (Exception e) {
                log.error("on get time error", e);
            }
            return jo;
        }).collect(Collectors.toList());
        return ld;
    }

    @Scheduled(cron = "0 0/10 * * * ?")
    public void checkOrder() {
        log.info("start check order");
        List<PaypalOrder> orders = lambdaQuery().eq(PaypalOrder::getStatus, "CREATED").list();
        if (orders != null && !orders.isEmpty()) {
            for (PaypalOrder order : orders) {
                try {
                    checkOne(order);
                } catch (IOException e) {
                    log.error("on check error", e);
                }
            }
        }
    }

    @Autowired
    PayPalService payPalService;

    private void checkOne(PaypalOrder o) throws IOException {
        JSONObject jd = payPalService.query(o.getId());
        if (jd.containsKey("status")) {
            String status = jd.getString("status");
            if ("APPROVED".equalsIgnoreCase(status)) {
                JSONObject jd0 = payPalService.capture(o.getId());
                if ("COMPLETED".equalsIgnoreCase(jd0.getString("status"))) {
                    o.setStatus("COMPLETED");
                    o.setData(jd.toJSONString());
                    updateById(o);
                    subscribeNow(o);
                }
            } else if ("COMPLETED".equalsIgnoreCase(status)) {
                o.setStatus("COMPLETED");
                o.setData(jd.toJSONString());
                updateById(o);
                subscribeNow(o);
            }
        }
    }

    @Autowired
    IRoleService roleService;

    @Override
    public void subscribeNow(PaypalOrder order) {
        long tsm = -1;
        if (order.getPrice() == 1) {
            tsm = (1000L * 60 * 60 * 24 * 1);
        } else if (order.getPrice() == 10) {
            tsm = (1000L * 60 * 60 * 24 * 30);
        } else if (order.getPrice() == 25) {
            tsm = (1000L * 60 * 60 * 24 * 90);
        } else if (order.getPrice() == 90) {
            tsm = (1000L * 60 * 60 * 24 * 365);
        }
        order.setStatus("COMPLETED");
        updateById(order);
        Role role;
        role = roleService.lambdaQuery().eq(Role::getUserId, order.getUid()).eq(Role::getUserRole, TokenManager.VIP).one();
        if (role != null) {
            if (role.getTimestamp() > System.currentTimeMillis()) {
                roleService.lambdaUpdate()
                        .eq(Role::getUserId, order.getUid())
                        .set(Role::getTimestamp, role.getTimestamp() + tsm)
                        .update();
            } else {
                roleService.lambdaUpdate()
                        .eq(Role::getUserId, order.getUid())
                        .set(Role::getTimestamp, System.currentTimeMillis() + tsm)
                        .update();
            }
        } else {
            role = new Role().setUserRole(TokenManager.VIP).setUserId(order.getUid())
                    .setTimestamp(System.currentTimeMillis() + tsm);
            roleService.save(role);
        }
    }
}
